<?php

class ACL {

	private static $cache;

	private $user;
	private $site;
	private $target;
	private $permission = 0;

	private function __construct($data = array()){
		foreach($data as $k => $v){
			$this->$k = $v;
		}
	}

	public static function GetUserRaw($target, $user){
		if(!isset(ACL::$cache['user'][$user->id()][$target])){
			$result = Database::getInstance()->query("SELECT * from `acl` WHERE `user` = %u AND `site` = %u AND `target` = %s", $user->id(), Site::getInstance()->GetID(), $target);
			if(!($permission = $result->fetch_object('ACL'))){
				$permission = new ACL(array('user' => $user->id(), 'site' => Site::getInstance()->GetID(), 'target' => $target));
			}
			ACL::$cache['user'][$user->id()][$target] = $permission;
		}
		return ACL::$cache['user'][$user->id()][$target];
	}

	public static function GetUser($user, $target, $permissions){
		$targets = array();
		$t = explode('/', $target);
		$base = '';
		foreach($t as $potential){
			$targets[] = $base . $potential;
			$base = $potential . '/';
		}

		$targets[] = '';

		$permission = 0;

		foreach($targets as $target){
			$perm = ACL::GetUserRaw($target, $user);
			if($perm->permission == -1){
				return $permissions;
			}
			$permission = $permission | $perm->permission;
		}

		$result = array();

		foreach($permissions as $k => $perm){
			if($permission & 1){
				$result[$k] = $perm;
			}
			$permission = $permission >> 1;
		}

		return $result;
	}




}
